import {Component, ElementRef, OnInit, ViewChild, ViewChildren} from '@angular/core';
import {List} from 'linqts';
import {ActivatedRoute, Router} from '@angular/router';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {ApplicationService} from '../../../service/application.service';
import {Farm} from '../../../entity/farm.model';
import {DatePipe} from '@angular/common';
import {LimitedFarm} from '../main/limited-farm';
import {LimitedPhases} from '../turbine-list/limited-phases';
import {LimitedCircuit} from '../turbine-list/limited-circuit';
import {DeviceComponent} from '../inverter-list/device/device.component';
import {TurbStatus} from '../../../entity/turbstatus.model';
import {Phase} from '../../../entity/phase.model';
import {Circuit} from '../../../entity/circuit.model';
import {CircuitService} from '../../../service/circuit.service';
import {TurbStatusService} from '../../../service/turbstatus.service';
import {PhaseService} from '../../../service/phase.service';
import {Device} from '../../../entity/device.model';
import {DeviceService} from '../../../service/device.service';
import {LimitedDevice} from '../inverter-list/limited-device';
import {LimitedTurbStatus} from '../turbine-list/limited-turbStatus';
import {FarmCategoryEnum} from '../../common/device-tag-selector/farm-category.enum';
import {InterceptorService} from '../../../service/interceptor/interceptor-service';


@Component({
  selector: 'app-inverter-list',
  templateUrl: './inverter-list.component.html',
  styleUrls: ['./inverter-list.component.css']
})
export class InverterListComponent implements OnInit {
  @ViewChildren(DeviceComponent)
  DeviceComp: DeviceComponent[];
  @ViewChild('main', {static: true})
  main: ElementRef;

  //默认颜色
  colorString: string = '#a6a3a3';
  //当前风场
  public currentFarm: LimitedFarm;
  farm: Farm;
  farmId: number = 0;
  active: number = null;
  //风场类别
  farmCategory: FarmCategoryEnum = FarmCategoryEnum.photovoltaic;
  /**
   * 设备列表
   */
  devices: Device[];

  /**
   * 逆变器数据
   *
   * @type {LimitedTurbine[]}
   * @memberof TurbineListComponent
   */
  public limitedDevices: LimitedDevice[] = [];
  /**
   * 状态数据
   */
  public limitedTurbstatus: LimitedTurbStatus[] = [];

  /**
   * 线路数据
   *
   * @type {LimitedCircuit[]}
   * @memberof TurbineListComponent
   */
  public limitedCircuits: LimitedCircuit[] = [];
  public tempLimitedCircuits: LimitedCircuit[] = [];
  public result: LimitedCircuit[] = [];

  /**
   * 分期数据
   *
   * @type {LimitedCircuit[]}
   * @memberof TurbineListComponent
   */
  public limitedPhases: LimitedPhases[] = [];
  public tempLimitedPhases: LimitedPhases[] = [];

  /**
   * 所有选中项对应的逆变器列表
   */
  public allCheckDeviceList: LimitedDevice[] = [];

  /**
   * 数据源服务
   */
  private dataSource: DataSourceService;
  /**
   * 倍率
   */
  public ratio: number = 1;

  /**
   * 所有选中的逆变器及区域
   */
  allCheckDeviceSubArrayList: any[] = [];
  /**
   * 区域Id集合
   */
  allCheckDeviceSubArrayIds: number[] = [];
  /**
   * 缩放大小
   *
   * @type {1}
   * @memberof InverterListComponent
   */
  zoom = 1;

  constructor(
    private application: ApplicationService,
    private activatedRoute: ActivatedRoute,
    private http: InterceptorService,
    private router: Router,
    private datePipe: DatePipe,
    private deviceService: DeviceService,
    private TurbStatusService: TurbStatusService,
    private phaseService: PhaseService,
    private circuitService: CircuitService,
  ) {
  }

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: { farmId: number }) => {
      if (params.farmId) {
        this.farmId = params.farmId;
      }
    });
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['ratio']) {
      this.ratio = Number(this.application.currentApplicationParams['ratio'].paramValue);
    }
  }

  //销毁指令
  ngOnDestroy(): void {
    if (this.dataSource != null)
      this.dataSource.dispose();
  }

  /**
   * 风场选中项变化
   */
  public onChangeFarm(farm: Farm) {
    if (farm != null) {
      this.active = null;
      this.loadData(farm);
    }
  }

  /**
   * 创建风场模型
   */
  private createLimitedFarm(farm: Farm) {
    if (farm != null) {
      let PowerDay = this.application.tagDict['PowerDay'];//日发电量
      let radiantQuantity = this.application.tagDict['radiation'];//辐射量
      let Power = this.application.tagDict['Power'];//有功功率
      // let Communication = this.application.tagDict["YC36"];//总发电量
      // console.log(Power,radiantQuantity)
      //创建风场数据模型
      this.currentFarm = new LimitedFarm();
      this.currentFarm.farmId = farm.farmId;
      this.currentFarm.farmCode = farm.farmCode;
      this.currentFarm.farmName = farm.farmName;
      this.currentFarm.farmCategory = farm.farmCategory;
      this.currentFarm.posx = farm.posx;
      this.currentFarm.posy = farm.posy;
      this.currentFarm.simpleCode = farm.simpleCode;
      this.currentFarm.capacity = farm.capacity;
      this.currentFarm.productionDate = farm.productionDate;
      this.currentFarm.totalTurbine = farm.totalTurbine;

      //创建实时数据点
      this.currentFarm.powerDay = this.dataSource.binding([farm.farmCode], PowerDay);
      this.currentFarm.radiantQuantity = this.dataSource.binding([farm.farmCode], radiantQuantity);
      this.currentFarm.totalPower = this.dataSource.binding([farm.farmCode], Power);
      // this.currentFarm.communication = this.dataSource.binding([farm.farmCode], Communication);
    }
  }

  /**
   * 创建逆变器状态
   *
   */
  private createLimitedDericeStatus(turbStatus: TurbStatus[]) {
    if (!turbStatus) return false;
    this.limitedTurbstatus = [];
    turbStatus.forEach(turbStatu => {
      let limitedTurbstatu = {
        id: turbStatu.statusId,
        name: turbStatu.statusName,
        value: turbStatu.statusValue,
        color: turbStatu.statusColor,
        tole: 0,
        isChecked: false,
      }
      this.limitedTurbstatus.push(limitedTurbstatu)
    })
  }

  /**
   * 创建分期
   */
  private createLimitedPhases(phases: Phase[], device: Device[]) {
    if (!phases || !device) return false;

    this.limitedPhases = [];
    // let GridMerPower = this.application.tagDict["YC19"];//并网有功P
    // let GriReaPower = this.application.tagDict["YC34"];//并网无功Q
    // let powerDay = this.application.tagDict["YC35"];//日发电量
    let Power = this.application.tagDict['Power'];//有功功率
    let radiantQuantity = this.application.tagDict['radiation'];//辐射量

    phases.forEach(phase => {
      let limitedPhase: LimitedPhases = {
        id: phase.phaseId,
        name: phase.phaseName,
        value: device.filter(o => o.phaseId == phase.phaseId).length,
        powers: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], Power),//有功功率
        radiantQuantity: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], radiantQuantity),//辐射量
        // powerDay: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], powerDay),//日发电量
        // GridMerPower: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], GridMerPower),//并网有功P
        // GriReaPower: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], GriReaPower),//并网无功Q
        isChecked: false
      };
      this.limitedPhases.push(limitedPhase)
    });
    this.tempLimitedPhases = [...this.limitedPhases];
    // console.log(this.tempLimitedPhases)
  }

  /**
   * 创建线路
   */
  private createLimitedCircuit(devices: Device[], circuits: Circuit[]) {
    if (!circuits || !devices) return false;
    this.limitedCircuits = [];
    circuits.forEach(circuit => {
      var count = 0;
      devices.forEach(device => {
        if (circuit.circuitId == device.circuitId) {
          count++;
        }
      })
      let limitedCircuit = {
        id: circuit.circuitId,
        name: circuit.circuitName,
        value: count,
        phaseIds: circuit.phaseIds,
        isChecked: false
      }
      this.limitedCircuits.push(limitedCircuit)
    })
    this.result = [...this.limitedCircuits];
    this.tempLimitedCircuits = [...this.limitedCircuits];
  }

  /**
   * 创建逆变器模型
   */
  private createLimitedDevice(devices: Device[]) {
    if (!devices) return false;
    this.limitedDevices = [];
    if (this.currentFarm != null) {
      let powerDay = this.application.tagDict['nbqPowerDay'];//日发电量
      let GriReaPower = this.application.tagDict['nbqGriReaPower'];//无功功率
      let TurbineStatus = this.application.tagDict['TurbineStatus'];//逆变器状态
      //光伏状态 添加code  吉林定制
      // TurbineStatus.tagCode = 'INVSTA';
      let subState = this.application.tagDict['GP'];//子状态
      let ActivePower = this.application.tagDict['nbqActivePower'];//有功功率
      if (this.currentFarm.farmId == 193 && this.currentFarm.farmCode === 'MM.MX_MM') {
        ActivePower = this.application.tagDict['MMnbqActivePower'];//有功功率
      }
      devices.forEach(device => {
        device.farmName = this.farm.farmName;
        let limitedDevice: LimitedDevice = {
          name: device.deviceName,
          powerDay: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], powerDay),//日发电量
          turbineStatus: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], TurbineStatus),//设备状态
          turbStatusColor: '#23d678',
          phaseId: device.phaseId,
          circuitId: device.circuitId,
          device: device,
          turbSubState: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], subState),//子状态
          GridMerPower: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], ActivePower),//有功功率
          GriReaPower: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], GriReaPower),//无功功率
          subArraryId: device.subArrayId,
          subArrayName: device.subArrayName,
        }
        this.limitedDevices.push(limitedDevice);
      })
    }
    this.allCheckDeviceList = this.limitedDevices;
    this.allCheckDeviceSubArrayList = [];
    this.allCheckDeviceSubArrayIds = [];
    this.allCheckDeviceList.forEach(checkDevice => {
      this.allCheckDeviceSubArrayIds.push(checkDevice.subArraryId)
    })
    this.allCheckDeviceSubArrayIds = Array.from(new Set(this.allCheckDeviceSubArrayIds))
    this.allCheckDeviceSubArrayIds.forEach(id => {
      this.allCheckDeviceSubArrayList.push(this.allCheckDeviceList.filter(a => a.subArraryId == id))
    })
  }

  /**
   * 获取对应的逆变器列表
   */
  private getDeviceList() {
    let checkTurbStatuList: LimitedTurbStatus[] = [];
    let checkTurPhaseList: LimitedPhases[] = [];
    let checkCircuitList: LimitedCircuit[] = [];

    checkTurbStatuList = this.limitedTurbstatus.filter(o => o.isChecked); //过滤选中的状态
    checkTurPhaseList = this.tempLimitedPhases.filter(o => o.isChecked);  //过滤选中的工期
    checkCircuitList = this.result.filter(o => o.isChecked);              //过滤选中的线路
    if (checkTurbStatuList.length > 0 || checkTurPhaseList.length > 0 || checkCircuitList.length > 0) {

      //将本地风机集合放入临时变量中
      let listTemp = [...this.limitedDevices];

      if (checkTurbStatuList.length > 0) {
        let list = new List(checkTurbStatuList).Select(o => o.value).ToList();
        listTemp = listTemp.filter(o => list.Contains(o.turbineStatus.value));
        this.tempLimitedPhases.forEach(v => {
          v.value = 0;
        })
        this.tempLimitedCircuits.forEach(v => {
          v.value = 0;
        });
        listTemp.forEach(v => {
          let i = this.limitedPhases.findIndex(o => o.id == v.phaseId);
          if (i > -1) {
            this.tempLimitedPhases[i].value += 1;
          }
          i = this.limitedCircuits.findIndex(o => o.id == v.circuitId);
          if (i > -1) {
            this.tempLimitedCircuits[i].value += 1;
          }
        });
      } else {
        this.tempLimitedCircuits.forEach(v => {
          v.value = this.devices.filter(o => o.circuitId == v.id).length;
        })
        this.tempLimitedPhases.forEach(v => {
          v.value = this.devices.filter(o => o.phaseId == v.id).length;
        })
      }
      this.result = [...this.tempLimitedCircuits]
      if (checkTurPhaseList.length > 0) {
        let list = new List(checkTurPhaseList).Select(o => o.id).ToList();
        listTemp = listTemp.filter(o => list.Contains(o.phaseId));
        this.tempLimitedCircuits.forEach(v => {
          v.value = 0;
        });
        listTemp.forEach(v => {
          let i = this.limitedCircuits.findIndex(o => o.id == v.circuitId);
          if (i > -1) {
            this.tempLimitedCircuits[i].value += 1;
          }
        });
        this.result = this.tempLimitedCircuits.filter(o => o.value != 0);
      }
      if (checkCircuitList.length > 0) {
        let list = new List(checkCircuitList).Select(o => o.id).ToList();
        listTemp = listTemp.filter(o => list.Contains(o.circuitId));
      }
      this.allCheckDeviceList = listTemp;
      this.allCheckDeviceSubArrayList = [];
      this.allCheckDeviceSubArrayIds = [];
      this.allCheckDeviceList.forEach(checkDevice => {
        this.allCheckDeviceSubArrayIds.push(checkDevice.subArraryId)
      })
      this.allCheckDeviceSubArrayIds = Array.from(new Set(this.allCheckDeviceSubArrayIds))
      this.allCheckDeviceSubArrayIds.forEach(id => {
        this.allCheckDeviceSubArrayList.push(this.allCheckDeviceList.filter(a => a.subArraryId == id))
      })


    }
    else {
      if (this.allCheckDeviceList.length != this.limitedDevices.length) {
        this.allCheckDeviceList = this.limitedDevices;
        //==============
        this.allCheckDeviceSubArrayList = [];
        this.allCheckDeviceSubArrayIds = [];
        this.allCheckDeviceList.forEach(checkDevice => {
          this.allCheckDeviceSubArrayIds.push(checkDevice.subArraryId)
        })
        this.allCheckDeviceSubArrayIds = Array.from(new Set(this.allCheckDeviceSubArrayIds))
        this.allCheckDeviceSubArrayIds.forEach(id => {
          this.allCheckDeviceSubArrayList.push(this.allCheckDeviceList.filter(a => a.subArraryId == id))
        })
        this.result = [...this.limitedCircuits];             //页面绑定线路

        // this.tempLimitedPhases = [...this.limitedCircuits];
        this.tempLimitedPhases = [...this.limitedPhases];//页面绑定工期

        this.limitedCircuits = [...this.limitedCircuits];

        this.tempLimitedCircuits.forEach(v => {
          v.value = this.devices.filter(o => o.circuitId == v.id).length;
        })
        this.tempLimitedPhases.forEach(v => {
          v.value = this.devices.filter(o => o.phaseId == v.id).length;
        })
      }
    }
    this.onResize();
  }

  /**
   * 统计逆变器状态
   */
  private countTurbStatus() {
    this.limitedDevices.forEach(device => {
      let index = this.limitedTurbstatus.findIndex(o => o.value == device.turbineStatus.value);
      if (index >= 0) {
        device.turbStatusColor = this.limitedTurbstatus[index].color;
      }
      else {
        // 未知
        device.turbStatusColor = this.colorString;
      }
    })
    //统计逆变器状态对应的逆变器数量
    this.limitedTurbstatus.forEach(status => {
      let list = new List(this.limitedDevices);
      status.tole = list.Count(o => o.turbineStatus.value == status.value)
    })
    //获取对应的逆变器列表
    this.getDeviceList();
  }

  /**
   * 加载数据
   */
  private loadData(farm: Farm) {
    this.farm = farm;
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
    this.dataSource = new DataSourceService(this.http, this.datePipe);
    this.createLimitedFarm(farm);

    let turbstatusGet: Promise<TurbStatus[]> = this.TurbStatusService.getInverterStatus();//逆变器状态列表
    let phaseGet: Promise<Phase[]> = this.phaseService.getPhasesByfarmId(farm.farmId);//通过farmId获取的分期
    let deviceGet: Promise<Device[]> = this.deviceService.getInvertersByFarmId(farm.farmId);//通过farmId获取的逆变器列表
    let circuitGet: Promise<Circuit[]> = this.circuitService.getCircuitByFarmId(farm.farmId);//通过farmId获取的线路

    Promise.all([turbstatusGet, phaseGet, deviceGet, circuitGet])
      .then(res => {
        if (res[2]) {
          this.devices = [...res[2]];
        }
        this.createLimitedDericeStatus(res[0]);
        this.createLimitedPhases(res[1], res[2]);
        this.createLimitedCircuit(res[2], res[3]);
        this.createLimitedDevice(res[2]);

        //开始推数据
        this.dataSource
          .begin()
          .subscribe(
            next => {
              this.countTurbStatus();
              this.DeviceComp.forEach(val => {
                val.initData()
              })
            },
            error => {
              console.log('app-photovoltaic-list', error);
            });
      })
      .catch(error => {
        console.log('app-photovoltaic-list', error);
      });
  }

  /**
   * 风机状态点击事件
   */
  public turbStatuClick(e: any, turbineStatu: LimitedTurbStatus) {
    turbineStatu.isChecked = turbineStatu.isChecked ? false : true;
    this.getDeviceList()
  }

  /**
   * 分期列表点击事件
   */
  public phaseClick(e: any, phase: LimitedPhases) {
    phase.isChecked = phase.isChecked ? false : true;
    this.getDeviceList();
  }

  /**
   * 集成电路点击事件
   */
  public circuitClick(e: any, circuit: LimitedCircuit) {
    circuit.isChecked = circuit.isChecked ? false : true;
    this.getDeviceList()
  }

  /**
   * 逆变器双击事件
   */
  public ondblclick(item: Device) {
    this.router.navigate(['/monitor/inverterdetail', item.farmId, item.deviceId]);
  }

  onResize() {

    const clientHeight = this.main.nativeElement.clientHeight,
      clientWidth = this.main.nativeElement.clientWidth;
    let turbConunt = 0;
    this.allCheckDeviceSubArrayList.forEach(o => {
      if (o) {
        turbConunt += o.length;
      }

    });
    let count = Math.floor(clientWidth / 150) * Math.floor(clientHeight / 100);
    if (count < turbConunt) {
      count = Math.floor(clientWidth / (150 * 0.9)) * Math.floor(clientHeight / (100 * 0.9));
      if (count < turbConunt) {
        this.zoom = 0.8;
      } else {
        this.zoom = 0.9;
      }
    } else {
      this.zoom = 1;
    }
  }
}


// WEBPACK FOOTER //
// ./src/app/module/monitor/inverter-list/inverter-list.component.ts
